package com.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boot.entity.Comment;
import com.boot.entity.User;
import com.boot.mapper.CommentMapper;
import com.boot.service.ICommentService;
import com.boot.service.IUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {
    @Resource
    private IUserService userService;

    @Override
    public List<Comment> getApprovedCommentsByQuestionId(Long questionId) {
        // 查询所有评论
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        wrapper.eq("question_id", questionId)
                .orderByDesc("created_at");
        List<Comment> comments = this.list(wrapper);

        if (comments.isEmpty()) return comments;

        // 获取所有评论者的 ID
        List<Long> userIds = comments.stream()
                .map(Comment::getUserId)
                .distinct()
                .collect(Collectors.toList());

        // 查询用户名
        QueryWrapper<User> userWrapper = new QueryWrapper<>();
        userWrapper.in("id", userIds).select("id", "username");
        List<User> users = userService.list(userWrapper);

        Map<Long, String> usernameMap = users.stream()
                .collect(Collectors.toMap(User::getId, User::getUsername));

        // 填充用户名
        comments.forEach(c -> c.setUsername(usernameMap.getOrDefault(c.getUserId(), "未知用户")));

        return comments;
    }
}
